<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['zndd:calendar:add']">新增休息日</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-zoom-in" size="mini" @click="selectCalendar">查看休息日列表</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['zndd:calendar:export']">导出休息日</el-button>
      </el-col>
      <el-col :span="1.5">
            <el-button
              type="info"
              plain
              icon="el-icon-upload2"
              size="mini"
              @click="handleImport"
              v-hasPermi="['zndd:calendar:import']"
            >导入</el-button>
          </el-col>
          <el-col :span="1.5" style="float: right;">
          <el-date-picker
            v-model="monthValue"
            type="month"
            size="mini"
            style="width:150px"
            @change="changeMonth"
            :clearable="false"
          ></el-date-picker>
        </el-col>
    </el-row>
    <el-calendar v-model="calendarMonth">
            <template slot="dateCell" slot-scope="{date, data}">
                {{ data.day.split('-').slice(1).join('-') }}
                <el-tag type="success" v-if="scheduleData[data.day]">
                    休息日
                </el-tag>
                <el-tag type="warning" v-if="!scheduleData[data.day]">
                    工作日
                </el-tag>
            </template>
        </el-calendar>
        <!-- 添加休息日信息对话框 -->
    <el-dialog title="新增休息日" :visible.sync="addOpen" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="休息日" prop="calendarDate">
            <el-date-picker
              v-model="form.calendarDate"
              type="date"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              placeholder="选择休息日">
            </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 查看休息日对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" @click="handleDelete"
          v-hasPermi="['zndd:calendar:remove']">删除休息日</el-button>
      </el-col>
    </el-row>
    <el-table v-loading="loading" :data="dateList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" label="序号" />
      <el-table-column label="休息日" align="center" prop="calendarDate" />
    </el-table>
    </el-dialog>
    <!-- 休息日导入对话框 -->
    <el-dialog style="align-content: center;" :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCalendar, getCalendar, delCalendar, addCalendar, updateCalendar ,listAllCalendar,listAllDataCalendar} from "@/api/zndd/rest/calendar";
import { getToken } from "@/utils/auth";

export default {
  name: "Calendar",
  data() {
    return {
      scheduleData: {
            },
      // 工位信息表格数据
      dateList: [],
      // 表单参数
      form: {},
      // 选中数组
      ids: [],
      //时间月份选择器
      monthValue:new Date(),
      //日历值
      calendarMonth:new Date(),
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 遮罩层
      loading: false,
      // 是否显示弹出层
      addOpen: false,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //导入参数
      upload: {
        // 是否显示弹出层（休息日导入）
        open: false,
        // 弹出层标题（休息日导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的休息日数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/zndd/calendar/importData"
      },
      // 表单校验
      rules: {
        calendarDate: [
          { required: true, message: "休息日不能为空", trigger: "blur" }
        ],
      },

    };
  },
  created() {
    this.getCalendarList()
  },
  methods: {
    //获取休息日列表
    getCalendarList(){
      listAllCalendar().then(response => {
        this.scheduleData = response.rows[0];
      });
    },
    //月份改变事件
    changeMonth(){
      this.calendarMonth = new Date(this.monthValue);
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除选中的休息日信息？').then(function () {
        return delCalendar(ids);
      }).then(() => {
        this.getDataList();
        this.getCalendarList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          console.log(this.form.calendarDate)
            var dates = this.form.calendarDate.split("-");
            this.form={};
            this.form.calendarYear = parseInt(dates[0]);
            this.form.calendarMonth = parseInt(dates[1]);
            this.form.calendarDay = parseInt(dates[2]);
            addCalendar(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.addOpen = false;
              this.getCalendarList();
            });
        }
      });
    },
    // 取消按钮
    cancel() {
      this.addOpen = false;
      this.form={};
    },
    //新增休息日
    handleAdd(){
      this.form={};
      this.addOpen = true;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 查询列表按钮 */
    selectCalendar() {
      this.open = true;
      this.title = "查看休息日列表信息";
      this.loading = true;
      this.getDataList();
    },
    /**弹出框获取休息日列表 */
    getDataList(){
      listAllDataCalendar().then(response => {
        var list = [];
        response.rows.forEach(row => {
          if(row.calendarMonth < 10){
            list.push({
                id:row.id,
                calendarDate:row.calendarYear+"-0"+row.calendarMonth+"-"+row.calendarDay
              })
          }else{
            list.push({
                id:row.id,
                calendarDate:row.calendarYear+"-"+row.calendarMonth+"-"+row.calendarDay
              })
          }
        });
        for (let i = 0; i < list.length-1; i++) {
          for (let j = 0; j < list.length-i-1; j++) {
            if(list[j].calendarDate < list[j+1].calendarDate){
              let tmp = list[j];
              list[j] = list[j+1];
              list[j+1] = tmp;
            }
          }
        }
        this.dateList = list;
        this.loading = false;
      });
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "休息日导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('zndd/calendar/importTemplate', {
      }, `休息日导入信息_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getCalendarList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('zndd/calendar/export', {
        ...this.queryParams
      }, `休息日信息_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style lang="scss" scoped>
::v-deep .el-calendar__header {
    display: none;
  }
</style>
